<template>
  <a-spin :spinning="loading">
    <a-form :form="form" ref="form" :label-col="labelCol" :wrapper-col="wrapperCol">
      <div v-for="(field, fieldIndex) in fieldItemOptions" :key="field.key">
        <a-form-item :label="field.label" :required="field.required" v-if="!field.hidden">
          <!-- text文本框 -->
          <template v-if="field.type === 'text'">
            <MyInput
              v-decorator="[
                field.key,
                {
                  rules: [
                    {
                      required: field.required,
                      message: `${field.label}不能为空`,
                    },
                  ],
                  initialValue: field.value,
                },
              ]"
              v-model="model[field.key]"
              :placeholder="`请输入${field.label}`"
              :disabled="field.disabled"
              v-bind="field.props"
            ></MyInput>
          </template>

          <!-- textarea 文本域 -->
          <template v-else-if="field.type === 'textarea'">
            <a-textarea
              v-decorator="[
                field.key,
                {
                  rules: [
                    {
                      required: field.required,
                      message: `${field.label}不能为空`,
                    },
                  ],
                  initialValue: field.value,
                },
              ]"
              :placeholder="`请输入${field.label}`"
              :disabled="field.disabled"
              v-bind="{ ...field.props }"
            />
          </template>

          <!-- select下拉框 -->
          <template v-else-if="field.type === 'select'">
            <a-select
              :placeholder="`请选择${field.label}`"
              v-decorator="[
                field.key,
                {
                  rules: [
                    {
                      required: field.required,
                      message: `请选择${field.label}`,
                    },
                  ],
                  initialValue: field.value,
                },
              ]"
              v-bind="{ ...field.props }"
              @change="handleChange($event, field, fieldIndex)"
            >
              <a-select-option v-for="option in field.options" :key="option.value" :value="option.value">{{
                option.label
              }}</a-select-option>
            </a-select>
          </template>

          <!-- checkbox多选框 -->
          <template v-else-if="field.type === 'checkbox'">
            <a-checkbox-group
              v-decorator="[
                field.key,
                {
                  rules: [
                    {
                      required: field.required,
                      message: `请选择${field.label}`,
                    },
                  ],
                  initialValue: field.value,
                },
              ]"
              v-bind="{ ...field.props }"
              @change="handleChange($event, field, fieldIndex)"
            >
              <a-checkbox
                v-for="option in field.options"
                :key="option.value"
                :value="option.value"
                :style="{ width: field.width }"
                >{{ option.label }}</a-checkbox
              >
            </a-checkbox-group>
          </template>

          <!-- radio单选框 -->
          <template v-else-if="field.type === 'radio'">
            <a-radio-group
              v-decorator="[
                field.key,
                {
                  rules: [
                    {
                      required: field.required,
                      message: `请选择${field.label}`,
                    },
                  ],
                  initialValue: field.value,
                },
              ]"
              v-bind="{ ...field.props }"
              @change="handleChange($event, field, fieldIndex)"
            >
              <a-radio v-for="option in field.options" :key="option.value" :value="option.value">{{
                option.label
              }}</a-radio>
            </a-radio-group>
          </template>

          <template v-else-if="field.type === 'datePicker'">
            <a-date-picker
              :placeholder="`请选择${field.label}`"
              v-decorator="[
                field.key,
                {
                  rules: [
                    {
                      required: field.required,
                      message: `请选择${field.label}`,
                    },
                  ],
                  initialValue: field.value,
                },
              ]"
              v-bind="{ ...field.props }"
            >
            </a-date-picker>
          </template>
        </a-form-item>
      </div>
    </a-form>
  </a-spin>
</template>
  
  <script>
import { deepClone } from '@/utils/deepClone'
import MyInput from './myInput'
export default {
  components: { MyInput },
  props: {
    // 表单域配置
    fieldOptions: {
      type: Array,
      default: () => [],
    },

    // 编辑时表单回显的默认数据
    model: {
      type: Object,
      default: () => ({}),
    },

    // 标签宽度
    labelCol: {
      type: Object,
      default: () => {
        return {
          xs: { span: 24 },
          sm: { span: 6 },
        }
      },
    },

    // 控件宽度
    wrapperCol: {
      type: Object,
      default: () => {
        return {
          xs: { span: 24 },
          sm: { span: 16 },
        }
      },
    },
  },

  computed: {},

  data() {
    return {
      loading: false,
      fieldItemOptions: [],
      fieldItemRelativeOptions: [],
      form: this.$form.createForm(this, { name: 'dynamic-form' }),
    }
  },
  methods: {
    // 初始化表单，只初始化一次，相比之前watch监听的写法，这里优化了性能
    async initForm() {
      this.loading = true
      const fieldOptions = deepClone(this.fieldOptions)
      //   for (let i = 0; i < fieldOptions.length; i++) {
      //     const c = fieldOptions[i]
      //     if (!c.props) c.props = {}
      //     c.value = this.model[c.key]
      //     for (const key in c) {
      //       if (c[key] && c[key] instanceof Function) {
      //         c[key] = await c[key](this.model)
      //       }
      //     }
      //   }
      this.fieldItemRelativeOptions = fieldOptions.filter((c) => (c ? (c.relativeList ? c.relativeList.length : 0) : 0))
      //   this.fieldItemOptions = deepClone(fieldOptions)
      this.fieldItemOptions = fieldOptions

      this.loading = false
    },

    // 提交表单
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.form.validateFields((err, formData) => {
          if (err) {
            reject(err)
            return
          }
          const formatFormData = this.formatFormData()
          for (const key in formatFormData) {
            formatFormData[key](formData)
          }
          // 提交表单逻辑
          console.log('表单数据：', formData)
          resolve(formData)
        })
      })
    },

    // 表单数据格式化
    formatFormData() {
      return {
        // datePicker类型
        datePicker: (formData) => {
          console.log('datePicker', formData)
          const type = this.fieldItemOptions.filter((c) => c.type === 'datePicker')
          if (type.length) {
            type.forEach((c) => {
              formData[c.key] = formData[c.key].format('YYYY-MM-DD')
            })
          }
        },
        // 其他类型
      }
    },

    // 处理关联表单项，只处理关联项，相比之前写onValuesChange优化了性能
    handleChange(e, field, fieldIndex) {
      if (this.fieldItemRelativeOptions.length) {
        this.fieldItemRelativeOptions.forEach((c) => {
          if (c.key === field.key) {
            c.relativeList.forEach((d) => {
              const target = this.fieldOptions.find((k) => k.key === d.key)
              const targetIndex = this.fieldOptions.findIndex((k) => k.key === d.key)
              d.props.forEach(async (x) => {
                this.fieldItemOptions[targetIndex][x] = await target[x](this.form.getFieldsValue())
              })
            })
          }
        })
      }
    },
  },
  mounted() {
    this.initForm()
  },
}
</script>
  